#include "camera.h"
#include "ui_camera.h"

#include <QTime>



camera::camera(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::camera)
{
    ui->setupUi(this);
    this->setWindowTitle("摄像头");

    //获取默认相机设备信息
      QCameraInfo dc = QCameraInfo::defaultCamera();
      qDebug()<<dc.description();

      //获取所有可用相机列表
      QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
      if(cameras.count() > 0)
      {
          foreach(const QCameraInfo &cameraInfo, cameras)
          {
              qDebug()<<cameraInfo.description();//相机描述信息
              qDebug()<<cameraInfo.deviceName();//设备的唯一ID  一串杂乱的编码
          }
          ca = new QCamera(cameras.at(0));
      }

      this->viewfinder = new QCameraViewfinder(ui->label);//实例化
      ui->label->setFixedSize(380,300);
      ui->label->setAlignment(Qt::AlignHCenter);
      //设置取景部位，普通部件使用 QCameraViewfinder
      //图形视图框架中使用 QGraphicsVideoItem
      ca->setViewfinder(viewfinder);
      viewfinder->setFixedSize(380,300);
      viewfinder->setAspectRatioMode(Qt::IgnoreAspectRatio);
//      find_view->setAspectRatioMode(Qt::IgnoreAspectRatio);
      //QCameraImageCapture图像录制，进行拍照
      this->imageCapture = new QCameraImageCapture(ca);

      // 连接捕捉到图像的信号与保存图像的槽函数
      connect(imageCapture, &QCameraImageCapture::imageCaptured, this, &camera::saveImage);
      ca->start();
      connect(ui->btn_take,&QPushButton::clicked,this,&camera::clicked);
}


camera::~camera()
{
  delete ui;
}

//拍照按钮
void camera::clicked()
{
  ca->setCaptureMode(QCamera::CaptureStillImage);
//  QString filename = QFileDialog::getSaveFileName();

  //捕捉图片时，先对相机进行锁定，完成捕捉后在进行解锁
//  ca->searchAndLock();
  // 捕捉图片并保存，异步函数，必须使用绝对路径;
  // 如果没有使用绝对路径，会将图片保存至默认目录;
  imageCapture->capture();
//  ca->unlock();
}

void camera::saveImage(int id, const QImage &preview)
{
    // 自动生成文件名
    QDir dir;
    dir.mkdir("./photos");
    QString name  ="./photos/" + QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".jpg";
    QString filename_f = name.arg(id);
//    QString filename_f = QString("./photos/image_%1.jpg").arg(id);

    // 保存图片
    if (!preview.save(filename_f)) {
        QMessageBox::critical(this,"failed","保存图片失败!");
        qDebug() << "保存图片失败!";
    } else {
        QMessageBox::information(this,"success",filename_f);
        qDebug() << "图片已保存至：" << filename_f;
    }
}

void camera::closeEvent(QCloseEvent *event)
{
    // 停止相机
    if (ca->state() == QCamera::ActiveState)
        ca->stop();

    // 调用父类的 closeEvent
    QWidget::closeEvent(event);
}
